/*
 * Copyright (c) 2011-2012  Cristian Constantin
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package com.quizio.engine;

import com.quizio.dao.UserDao;
import com.quizio.engine.dao.QuizRepository;
import com.quizio.engine.dao.QuizSessionDao;
import com.quizio.engine.model.Quiz;
import com.quizio.engine.model.QuizSession;
import com.quizio.engine.session.QuizSessionService;
import com.quizio.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Cristian Constantin
 * @since 1/3/12
 */
@Service
@Transactional
public class QuizPlanningService {

    @Autowired
    private QuizRepository quizRepository;

    @Autowired
    private UserDao userDao;

    @Autowired
    private QuizSessionDao sessionDao;

    @Autowired
    private QuizSessionService quizSessionService;

    /**
     * Returns the list of quizes that can be scheduled
     * by the current logged in user.
     *
     * @return the list of quizes
     */
    public List<Quiz> getAllQuizes() {
        return quizRepository.getAll();
    }

    /**
     * Returns the list of users that are allowed to be registered for exams.
     *
     * @return the list of users
     */
    public List<User> getAllUsers() {
        return userDao.getAll();
    }

    /**
     * Schedules a new quiz session for a list of users.
     *
     * @param quizId   the ID of the quiz to schedule
     * @param usersIds the IDs list of the users to schedule for exam
     */
    public void scheduleQuiz(Long quizId, Long[] usersIds) {

        Quiz quiz = quizRepository.getById(quizId);
        List<User> users = getUsersById(usersIds);

        List<QuizSession> sessions = new ArrayList<>();
        for (User user : users) {
            sessions.add(quizSessionService.createSession(quiz, user));
        }

        sessionDao.saveOrUpdateAll(sessions);
    }

    private List<User> getUsersById(Long[] ids) {
        List<User> users = new ArrayList<>();

        for (Long id : ids) {
            User user = new User();
            user.setId(id);
            users.add(user);
        }

        return users;
    }
}
